package com.ctrip.ibu.member.common.util;


import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author he.shaorong
 * @create 2023/3/27 15:26
 * @since 1.0.0
 */
public class HttpClientUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    public static JSONObject postJson(String url, String jsonParams) throws Exception {
        JSONObject jsonObject = null;

        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = null;
        // 接收响应结果
        CloseableHttpResponse response = null;
        try {
            // 创建httppost
            httpclient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
            // 参数
            StringEntity se = new StringEntity(jsonParams);
            se.setContentEncoding("UTF-8");
            se.setContentType("application/json");
            httpPost.setEntity(se);
            response = httpclient.execute(httpPost);

            logger.info("HttpClientUtil postJson response", response.toString());

            // 解析返结果
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                jsonObject = JSONObject.parseObject(EntityUtils.toString(entity, "UTF-8"));
            }
        } catch (Exception e) {
            logger.error("HttpClientUtil postJson error", e);
            throw e;
        } finally {
            httpclient.close();
            response.close();
            return jsonObject;
        }
    }

    /**
     * post方式提交表单（模拟用户登录请求）
     *
     * @throws Exception
     */
    public static JSONObject postForm(String url, Map<String, String> params) throws Exception {
        JSONObject jsonObject = null;

        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = null;
        // 发送请求
        CloseableHttpResponse response = null;
        try {
            httpclient = HttpClients.createDefault();
            // 创建httppost

            HttpPost httppost = new HttpPost(url);
            // 创建参数队列 ,通过一个NameValuePair集合来存放待提交的参数,并将这个参数集合传入到一个
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            // 设置参数
            for (String key : params.keySet()) {
                formparams.add(new BasicNameValuePair(key, params.get(key)));
            }
            // 参数转码
            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            response = httpclient.execute(httppost);

            logger.info("HttpClientUtil postForm response", response.toString());

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                jsonObject = JSONObject.parseObject(EntityUtils.toString(entity, "UTF-8"));
            }
            // 释放连接
        } catch (Exception e) {
            logger.error("HttpClientUtil postForm error", e);
            throw e;
        } finally {
            httpclient.close();
            response.close();
            return jsonObject;
        }
    }

    /**
     * 发送 get请求
     *
     * @throws Exception
     */
    public static JSONObject get(String url) throws Exception {
        JSONObject jsonObject = null;

        CloseableHttpClient httpclient = null;
        CloseableHttpResponse response = null;
        try {
            httpclient = HttpClients.createDefault();
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);
            // 执行get请求.
            response = httpclient.execute(httpget);
            // 获取响应实体
            HttpEntity entity = response.getEntity();

            logger.info("HttpClientUtil get response", response.toString());

            if (entity != null) {
                // 打印响应内容
                jsonObject = JSONObject.parseObject(EntityUtils.toString(entity, "UTF-8"));
            }
        } catch (Exception e) {
            logger.error("HttpClientUtil get error", e);
            throw e;
        } finally {
            httpclient.close();
            response.close();
            return jsonObject;
        }
    }
}
